package top.oneit.jdownload.data.dao;

import org.hibernate.Session;
import top.oneit.jdownload.constants.JConstants;
import top.oneit.jdownload.data.entity.DownloadSaveStatus;
import top.oneit.jdownload.data.entity.DownloadingTablePo;

import java.util.ArrayList;
import java.util.List;

public class DownloadingTablePoDao extends BaseDao {

    /**
     * 下载状态置为暂停
     */
    public static void initDownloadingToPause() {
        Session session = getSession();
        session.beginTransaction();
        List<String> list = new ArrayList<>(2);
        list.add(JConstants.FILE_STATUS_AWAIT_DOWNLOAD);
        list.add(JConstants.FILE_STATUS_DOWNLOADING);
        session.createQuery("update DownloadingTablePo set status=:newStatus where status in (:oldStatus)")
                .setParameter("oldStatus", list)
                .setParameter("newStatus", JConstants.FILE_STATUS_PAUSE)
                .executeUpdate();
        session.getTransaction().commit();
    }

    public static List<DownloadingTablePo> getNotFinish() {
        Session session = getSession();
        session.beginTransaction();
        List<DownloadingTablePo> list = session.createQuery(
                        "from DownloadingTablePo where status!=:status order by createTime desc"
                ).setParameter("status", JConstants.FILE_STATUS_FINISH)
                .list();
        session.getTransaction().commit();
        return list;
    }

    public static void updateStatus(Long id, String status) {
        Session session = getSession();
        session.beginTransaction();
        session.createQuery("update DownloadingTablePo set status=:status where id=:id")
                .setParameter("status", status).setParameter("id", id).executeUpdate();
        session.getTransaction().commit();
    }

    public static Integer getAlreadyDownloadSize(DownloadingTablePo po) {
        Session session = getSession();
        session.beginTransaction();
        List<DownloadSaveStatus> list = session.createQuery("from DownloadSaveStatus where downloadingTablePo=:po")
                .setParameter("po", po)
                .list();
        session.getTransaction().commit();
        if (list.isEmpty()) {
            return 0;
        }
        Integer res = 0;
        for (DownloadSaveStatus e : list) {
            res += (e.getCurrentPosition() - e.getStartPosition());
        }
        return res;
    }

}
